package de.velvettear.squirrel.adapter;

import java.util.Vector;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.Port;

public class PortAdapter extends ArrayAdapter {
	
	private Context context;
	
	private Vector<Port> ports;
				
	public PortAdapter(Context context, int layout, int textViewResourceId, Vector<Port> ports) {
		super(context, layout, textViewResourceId, ports);
		this.context = context;
		this.ports = ports;
	}
	
	@Override
	public int getCount() {
		return ports.size();
	}

	@Override
	public Port getItem(int position) {
		return ports.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		PortViewHolder viewHolder;
		Port port = ports.get(position);	
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.listview_ports, null);
			
			viewHolder = new PortViewHolder();
			viewHolder.iv_open = (ImageView) convertView.findViewById(R.id.listview_ports_open);
			viewHolder.tv_number = (TextView) convertView.findViewById(R.id.listview_ports_number);	
			viewHolder.icon_check = convertView.getResources().getDrawable(R.drawable.icon_check);
			viewHolder.icon_fail = convertView.getResources().getDrawable(R.drawable.icon_fail);
			
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (PortViewHolder) convertView.getTag();
		}	
				
		if (port.m_bOpen) {
			viewHolder.iv_open.setImageDrawable(viewHolder.icon_check);
		} else {
			viewHolder.iv_open.setImageDrawable(viewHolder.icon_fail);
		}
		viewHolder.tv_number.setText(String.valueOf(port.m_nNumber));
			
		return convertView;	
	}

	static class PortViewHolder {
		View convertView;
		ImageView iv_open;
		TextView tv_number;
		Drawable icon_check;
		Drawable icon_fail;
	}
	
}
